<template>
  <div class="article-management">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <h2>用户管理</h2>
          <el-button type="primary" @click="handleAdd" :icon="Plus">新增用户</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="用户名称" class="form-item">
            <el-input v-model="searchForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item class="form-item">
            <el-button type="primary" @click="onSearch" :icon="Search">搜索</el-button>
            <el-button @click="resetSearch" :icon="Refresh">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格区域 -->
      <div class="table-area">
        <el-table :data="userList" style="width: 100%" @selection-change="handleSelectionChange" :stripe="true" :border="true">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="username" label="用户名" min-width="180">
            <template #default="scope">
              <el-link type="primary" @click="viewArticle(scope.row)">{{ scope.row.username }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="introduce" label="简介" min-width="180">
            <template #default="scope">
              {{scope.row.introduce}}
            </template>
          </el-table-column>
          <el-table-column label="头像" width="180">
            <template #default="scope">
              <el-image
                  style="width: 100px; height: 100px"
                  :src="scope.row.avatar"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  :preview-src-list="[scope.row.avatar]"
                  :initial-index="4"
                  preview-teleported
                  fit="cover"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" type="primary" @click="handleEdit(scope.row)" :icon="Edit">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)" :icon="Delete">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-area">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="userTotal">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60%" destroy-on-close>
      <el-form :model="userForm" label-width="80px" class="article-form">
        <el-form-item label="用户名">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="userForm.introduce"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="userForm.password"></el-input>
        </el-form-item>
        <el-form-item>
          <!-- 上传图片 -->
          <el-upload class="avatar-uploader" accept="image/*" :show-file-list="false"
                     :http-request="uploadMainImg">
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar">
            <i v-else class="avatar-uploader-icon">
              <el-icon>
                <Plus />
              </el-icon>
            </i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitArticle">发布</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Plus, Delete, Edit } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { toast } from '@/composables/util.js'
import {selectAllUser, selectByUserId, deleteByUserId, addUser, updateUser} from '@/api/back/user.js'
import { uploadAvatarImage } from '@/api/common/web.js'
import store from "@/store"


// 搜索表单数据
const searchForm = reactive({
  username: ''
})

// 用户列表数据
const userList = ref([
  // { id: 1, name: 'Vue3', description: '321321' },
  // { id: 2, name: 'React', description: '2342'},
  // ... 更多用户数据
])

// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(5)
const userTotal = ref(100)


// 选中的用户
const selectedUsers = ref([])

// 对话框相关数据
const dialogVisible = ref(false)
const dialogTitle = ref('新增用户')
const userForm = reactive({
  id: null,
  username: '',
  introduce: '',
  avatar: ''
})

onMounted(async () => {
  InitDate()
})


//初始化数据
const InitDate = async () =>{
  await selectAllUser({pageNum: currentPage.value,pageSize: pageSize.value}).then((res) => {
    userList.value = res.data.data.list
    userTotal.value = res.data.data.total
  })
}


// 搜索方法
const onSearch = () => {
  console.log('搜索条件：', searchForm)
  selectAllUser({pageNum: currentPage.value,pageSize: pageSize.value, username: searchForm.username}).then(res => {
    userList.value = res.data.data.list
    userTotal.value = res.data.data.total
  })
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = Array.isArray(searchForm[key]) ? [] : null
  })
}


//上传图片
const uploadMainImg = function (file) {
  //创建表单结构
  console.log(file)
  const data = new FormData()
  data.append('file', file.file)

  uploadAvatarImage(data).then(res => {
    userForm.avatar = res.data.data[0].url
  })
}

// 新增用户
const handleAdd = () => {
  dialogTitle.value = '新增用户'
  Object.keys(userForm).forEach(key => {
    userForm[key] = Array.isArray(userForm[key]) ? [] : null
  })
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'

  Object.assign(userForm, row)
  console.log("编辑行",userForm)
  dialogVisible.value = true
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这篇用户吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteByUserId(row.id).then(res=>{
      toast("删除成功!","success")
      InitDate()
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

// 查看用户
const viewArticle = (row) => {
  console.log('查看用户：', row)
  // 这里应该跳转到用户详情页或打开预览对话框
}

// 提交用户
const submitArticle = () => {
  console.log('提交用户：', userForm)
  userForm.userId = store.state.userInfo.id
  if(userForm.id){
    updateUser(userForm).then(res => {
      if(res.data.code === '200'){
        toast( '用户更新成功',"success")
        InitDate()
      }
    })
  }else{
    console.log("我进入了新增:" ,userForm)
    addUser(userForm).then(res => {
      if(res.data.code === '200'){
        toast( '用户发布成功',"success")
        InitDate()
      }
    })
  }

  dialogVisible.value = false
  InitDate()
}

// 表格选择变化
const handleSelectionChange = (val) => {
  selectedUsers.value = val
}

// 改变每页显示数量
const handleSizeChange = (val) => {
  pageSize.value = val
  // 这里应该重新加载用户列表
  selectAllUser({pageNum: currentPage.value,pageSize: pageSize.value, username: searchForm.username}).then(res => {
    userList.value = res.data.data.list
    userTotal.value = res.data.data.total
  })
}

// 改变页码
const handleCurrentChange = (val) => {
  currentPage.value = val
  selectAllUser({pageNum: currentPage.value,pageSize: pageSize.value, username: searchForm.username}).then(res => {
    userList.value = res.data.data.list
    userTotal.value = res.data.data.total
  })
}
</script>

<style scoped>
.article-management {
  padding: 20px;

  min-height: 100vh;
}

.main-card {
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h2 {
  margin: 0;
  color: #1f2f3d;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.form-item {
  margin-bottom: 10px;
  flex-grow: 1;
}

/* 确保最后一个表单项(按钮组)不会过度拉伸 */
.form-item:last-child {
  flex-grow: 0;
}

.table-area {
  margin-bottom: 20px;
}

.tag-item {
  margin-right: 5px;
  margin-bottom: 5px;
}

.pagination-area {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.article-form {
  max-width: 600px;
  margin: 0 auto;
}

.el-dialog__body {
  padding-top: 10px;
}

.dialog-footer {
  text-align: right;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>